#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

#include "video-graphics.h"
#include "jogo.h"

// definicoes globais
void kbd_isr(void);
_go32_dpmi_seginfo old_kbd_irq, old_rtc_irq, old_irq;
volatile int rtc_ints = 0, rtc_upd_ints = 0, rtc_per_ints = 0, rtc_alarm_ints = 0;


void rtc_isr(void)
{
	Byte cause = read_rtc(RTC_STAT_C);
	
	if (cause & RTC_UF) // seconds interrupt
		rtc_upd_ints++;
	
	if (cause & RTC_AF) // alarm interrupt
		rtc_alarm_ints++;
	
	if (cause & RTC_PF) // periodic interrupt
		rtc_per_ints++;
		
	rtc_ints++;
	outportb(PIC1_CMD, EOI);
	outportb(PIC2_CMD, EOI);
}


// funcoes para o RTC

void init_rtc()
{
	install_c_irq_handler(RTC_IRQ, rtc_isr, &old_rtc_irq);
	rtc_int_enable();
	unmask_pic(RTC_IRQ);
}

void finalize_rtc()
{
	mask_pic(RTC_IRQ);
	rtc_int_disable();
	reinstall_c_irq_handler(RTC_IRQ, &old_rtc_irq);
}


int main()
{
	// definicoes para o timer
	timer_init(0, 0x36);
	timer_init(2, 0x36);
	
	// instalacao dos handlers
	install_asm_irq_handler(T0_IRQ, t0_isr, &old_irq);
	install_asm_irq_handler(KBD_IRQ, kbd_isr, &old_kbd_irq);
	
	// entrar em modo grafico
	int modo = 0x103;
	__dpmi_meminfo map;
	char* base = enter_graphics(modo, &map);
	
	// musica principal
	Note n[] = {{392, 5}, {392,10} , {329.63, 5}, {392, 5}, {392,10} , {329.63, 5}, {329.63, 5}, {349.23, 5}, {349.23, 5}, {392, 5}, {349.23, 5}, {329.63, 15}};
	Song s = {sizeof(n)/sizeof(Note), 1, n};
	
	// definicoes
	Sprite *back = create_sprite(background);
	Sprite *titulo = create_sprite(title);
	gameover = 0;
	int nivel = 1, dif_x = 7, dif_y = 5;
	
	// iniciar contador
	init_rtc();
	
	draw_sprite(titulo, base);
	play_song(&s);
	
	int old_s = scancode;
	while(old_s == scancode);
	
	// ciclo de estruturacao de niveis
	while(gameover == 0){
		draw_sprite(back, base);
		
		animate_game(dif_x, dif_y, nivel, base);
		
		++nivel;
		dif_x +=2;
		dif_y +=1;
		delay(3000);
	}
	
	destroy_sprite(titulo);
	// terminar contador
	finalize_rtc();
	
	// reinstalacao dos handlers
	reinstall_asm_irq_handler(KBD_IRQ, &old_kbd_irq);
	reinstall_asm_irq_handler(T0_IRQ, &old_irq);	
	
	// sair do modo grafico
	leave_graphics(map);
	
	return 0;
}
